//
// Created by liushuai on 2021/1/17.
//

#include "spiralOrder.h"

vector<int> spiralOrder(vector<vector<int> > &matrix) {
    vector<int> result;
    if (matrix.empty())
        return result;

    int rows = matrix.size();
    int cols = matrix[0].size();
    int center = min((rows - 1) / 2, (cols - 1) / 2);
    int layer;
    for (layer = 0; layer <= center; layer++) {
        for (int c = 0; c < cols - 1; c++) result.push_back(matrix[layer][layer + c]);
        for (int r = 0; r < rows - 1; r++) result.push_back(matrix[layer + r][layer + cols - 1]);
        // 当r=1或c=1时，只需要左上到右上和右上到右下的两步遍历，
        // 但会漏掉matrix[layer + rows - 1][layer + cols - 1]]，因此补上
        if (rows == 1 || cols == 1)
            result.push_back(matrix[layer + rows - 1][layer + cols - 1]);
        else {
            for (int c = cols - 1; c > 0; c--) result.push_back(matrix[layer + rows - 1][layer + c]);
            for (int r = rows - 1; r > 0; r--) result.push_back(matrix[layer + r][layer]);
        }
        rows -= 2;
        cols -= 2;
    }
    return result;
}
//vector<int> spiralOrder(vector<vector<int> > &matrix){
//    int rows = matrix.size();
//    vector<int> result;
//    if(rows==0)
//        return result;
//    int cols = matrix[0].size();
//    result = vector<int>(rows*cols,0);
//    int layers = rows/2;
//
//    int result_index = 0;
//    for(int layer_index = 0;layer_index<=layers-1;layer_index++){
//        for(int col=layer_index;col<rows-layer_index-1;col++)
//            result[result_index++]=matrix[layer_index][col];
//        for(int row=layer_index;row<rows-layer_index-1;row++)
//            result[result_index++] = matrix[row][cols-1];
//        for(int col=layer_index;col<rows-layer_index-1;col++)
//            result[result_index++] = matrix[rows-1][cols-1-col];
//        for(int row=layer_index;row<rows-layer_index-1;row++)
//            result[result_index++] = matrix[rows-1-row][layer_index];
//    }
//    int i=0;
//    while (result_index<=rows*cols){
//        result[result_index++] = matrix[rows/2][cols/2+i];
//        i+=1;
//    }
//
//
//    return result;
//}

